import gtk
import account


class appAccount:
    """Account settings application class"""
    def __init__(self):
        builder = gtk.Builder()
        builder.add_from_file("ui/account.glade")
        self.dialog = builder.get_object("dialogSettingsAccount")
        builder.connect_signals(self)
        #fill in account informations
        self._account = account.getMyAccount()
        self._nameEntry = builder.get_object("accountName")
        try:
            self._nameEntry.set_text(self._account.getName())
        except account.accountError:
            pass
        self._IDEntry = builder.get_object("accountIDEntry")
        try:
            self._IDEntry.set_text(self._account.getID())
        except account.accountError:
            pass
        self._keyEntry = builder.get_object("label_key_detect")
        try:
            self._account.getKey()
            self._keyEntry.set_text('Ready')
        except account.accountError:
            self._keyEntry.set_text('Missing')
        #populate netplugslistore
        self._netPlugsListstore = builder.get_object("netPlugsListstore")
        self.refreshNetPlugList()
        #get addnetplug dialogs
        self._addNetPlugDialog = builder.get_object("addNetPlugDialog")
        self._typeAddNetPlugDialogCombobox = builder.get_object("typeAddNetPlugDialogCombobox")
        self._tcpAddNetPlugVbox = builder.get_object("tcpAddNetPlugVbox")
        self._detailsAddNetPlugVbox = builder.get_object("detailsAddNetPlugVbox")
        self._netPlugTypesListstore = builder.get_object("netPlugTypesListstore")
        self._nameAddNetPlugEntry = builder.get_object("nameAddNetPlugEntry") 
        self._portTcpAddNetPlugEntry = builder.get_object("portTcpAddNetPlugEntry")
        self._ipTcpAddNetPlugEntry = builder.get_object("ipTcpAddNetPlugEntry")
        self._netPlugsTreeview = builder.get_object("netPlugsTreeview")
        
    def refreshNetPlugList(self):
        self._netPlugsListstore.clear()
        for netPlugParam in self._account.getNetPlugs():
            self._netPlugsListstore.append((netPlugParam.getName(),netPlugParam.getType()))
        
    def on_addNetPlugAction_activate(self,widget,data=None):
        self._addNetPlugDialog.run()

    def on_delNetPlugAction_activate(self,widget,data=None):
        selected = self._netPlugsTreeview.get_selection().get_selected_rows()[1]
        for rowSelected in selected:
            name = self._netPlugsListstore.get_value(self._netPlugsListstore.get_iter(rowSelected),0)
            self._account.delNetPlugByName(name)
        self.refreshNetPlugList()
    
    def on_buttonCancel_clicked(self,widget,data=None):
        self.dialog.destroy()
        
    def on_buttonOK_clicked(self,widget,data=None):
        #save account informations
        self._account.setName(self._nameEntry.get_text())
        self.dialog.destroy()
        
    def on_dialogSettingsAccount_close(self,widget,data=None):
        self.dialog.destroy()
        
    def on_buttonResetDatabase_clicked(self,widget,data=None):
        database.myDatabase.createDatabase()
        
    def on_button_key_gen_clicked(self,widget,data=None):
        self._account.generateNewKey()
        self._keyEntry.set_text('Ready')
    
    def on_buttonClear_clicked(self,widget,data=None):
        self._account.clearSettings()
        self.dialog.destroy()

    def on_exportAction_activate(self,widget,data=None):
        fc = gtk.FileChooserDialog("Save my account as a contact",None,gtk.FILE_CHOOSER_ACTION_SAVE,(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        filter = gtk.FileFilter()
        filter.add_pattern("*.dat")
        fc.set_filter(filter)
        fc.set_do_overwrite_confirmation(True)
        if fc.run() == gtk.RESPONSE_ACCEPT:
            if fc.get_filename()[-4:] != ".dat":
                friends.getFriendsPool().exportFriendFromFile(self._account,fc.get_filename()+'.dat')
            else:
                friends.getFriendsPool().exportFriendFromFile(self._account,fc.get_filename())
        fc.destroy()
        
    def on_cancelAddNetPlugDialogAction_activate(self,widget,data=None):
        self._addNetPlugDialog.hide()
        self._addNetPlugDialog.response(0)
    
    def on_typeAddNetPlugDialogCombobox_changed(self,widget,data=None):
        selected = self._netPlugTypesListstore.get_value(self._typeAddNetPlugDialogCombobox.get_active_iter(),0)
        if selected == "tcp":
            #remove last child and add new details panel
            self._detailsAddNetPlugVbox.remove(self._detailsAddNetPlugVbox.get_children()[-1])
            self._detailsAddNetPlugVbox.pack_end(self._tcpAddNetPlugVbox)
            
    def on_okAddNetPlugDialogAction_activate(self,widget,data=None):
        #create netplugparam from entries
        name = self._nameAddNetPlugEntry.get_text()
        type = self._netPlugTypesListstore.get_value(self._typeAddNetPlugDialogCombobox.get_active_iter(),0)
        if not name or not type:
            return
        specific = {}
        capabilities = None
        if type == net.NETPLUG_TYPE_TCP:
            capabilities = net.NETPLUG_CAPABILITY_SERVER | net.NETPLUG_CAPABILITY_CLIENT
            sport = self._portTcpAddNetPlugEntry.get_text()
            ip = self._ipTcpAddNetPlugEntry.get_text()
            if (not sport) or (not ip):
                return
            specific[net.NETPLUG_SPECIFIC_TCP_PORT] = int(sport)
            specific[net.NETPLUG_SPECIFIC_TCP_IP] = ip
        netplugparam = net.netPlugParam(name,type,capabilities,specific)
        #save netplugparam to account
        self._account.addNetPlug(netplugparam)
        #close dialog
        self._addNetPlugDialog.hide()
        self._addNetPlugDialog.response(1)
        self.refreshNetPlugList()